import { createI18n } from "vue-i18n";
import { type UserModule } from "@/types";

// Import i18n resources
// https://vitejs.dev/guide/features.html#glob-import
//
// Don't need this? Try vitesse-lite: https://github.com/antfu/vitesse-lite

const messages = Object.fromEntries(
  Object.entries(
    import.meta.glob<{ default: any }>("../../locales/*.y(a)?ml", {
      eager: true,
    })
  ).map(([key, value]) => {
    const yaml = key.endsWith(".yaml");
    return [key.slice(14, yaml ? -5 : -4), value.default];
  })
);

export const install: UserModule = ({ app, microEnv }) => {
  const i18n = createI18n({
    legacy: false,
    locale: microEnv?.locale ?? "zh-CN",
    fallbackLocale: "zh-CN", // set fallback locale
    messages,
  });

  app.use(i18n);
  if (window.__POWERED_BY_WUJIE__) {
    window.$wujie.bus.$on("i18n", (locale: string) => {
      i18n.global.locale.value = locale;
    });
  }
};
